#!/bin/bash

#-- Define function to process coordinates
function calc() {
	echo "scale=6; $1" | bc
}
function longTrans() {
	dir=$2
	deg=$(echo "$1" | cut -c-3)
	min=$(echo "$1" | cut -c4-)
	val=$(calc "$deg+$min/60")
	[ $dir = "W" ] && val=-$val
	echo " $val"
}
function latiTrans() {
	dir=$2
	deg=$(echo "$1" | cut -c-2)
	min=$(echo "$1" | cut -c3-)
	val=$(calc "$deg+$min/60")
	[ $dir = "S" ] && val=-$val
	echo " $val"
}
#-- Initialize variables
IFS=,
title="KinetaMap track";
[ $# -gt 0 ] && title="$1";
#-- Create temporal files
rm -rf tBlock cBlock hBlock fBlock;
touch cBlock tBlock hBlock fBlock;
#-- Writing down Header block
echo '<?xml version="1.0" encoding="UTF-8"?>' >> hBlock
echo '<kml xmlns="http://www.opengis.net/kml/2.2"' >> hBlock
echo 'xmlns:gx="http://www.google.com/kml/ext/2.2">' >> hBlock
echo '<Folder>' >> hBlock
echo "	<name>$title</name>" >> hBlock
echo '	<Style id="myLinestyle">' >> hBlock
echo '		<LineStyle>' >> hBlock
echo '			<color>ff0000ff</color>' >> hBlock
echo '			<width>4</width>' >> hBlock
echo '		</LineStyle>' >> hBlock
echo '	</Style>' >> hBlock
echo '	<Placemark>' >> hBlock
echo '		<styleUrl>#myLinestyle</styleUrl>' >> hBlock
echo '		<name>myTrack</name>' >> hBlock
echo '		<gx:Track>' >> hBlock
echo '			<altitudeMode>clampToGround</altitudeMode>' >> hBlock
#-- Writing down Footer block
echo '		</gx:Track>' >> fBlock
echo '	</Placemark>' >> fBlock
echo '</Folder>' >> fBlock
echo '</kml>' >> fBlock
#-- Process all lines from the standard input
while read line; do
	set -- $(echo "$line")
	if [ $3 = "A" -a $1 = '$GPRMC' ]; then
		rawTime=$(echo "$2" | cut -d. -f1);
		hh=$(echo "$rawTime" | cut -c1-2);
		mm=$(echo "$rawTime" | cut -c3-4);
		ss=$(echo "$rawTime" | cut -c5-6);
		latiVal=$(latiTrans $4 $5);
		longVal=$(longTrans $6 $7);
		shift
		DD=$(echo "$9" | cut -c1-2);
		MM=$(echo "$9" | cut -c3-4);
		YY=$(echo "$9" | cut -c5-6);
		cLine="			<gx:coord>$longVal $latiVal 0</gx:coord>";
		tLine="			<when>20$YY-$MM-$DD"T"$hh:$mm:$ss"Z"</when>";
		echo "$tLine" >> tBlock;
		echo "$cLine" >> cBlock;
	fi
done
#-- Output the result to the standard output
cat hBlock
cat tBlock
cat cBlock
cat fBlock
#-- Delete temporal files
rm -rf tBlock cBlock hBlock fBlock;